import {Component, OnInit} from '@angular/core';
import {flyIn} from "../../animations/flyIn.animation";

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.scss'],
  animations: [flyIn]
})
export class LineChartComponent implements OnInit {

  public echartsInstance: any;

  public echartsInstance3: any;

  public linechartOptions: any;

  public linechartOptions2: any;

  public linechartOptions3: any;

  public mockData = []; //模拟数据

  public nowTime = new Date(2017, 11, 10); //当前时间

  public timeInterval = 24 * 3600 * 1000; //时间间隔

  public randomValue = Math.random() * 1000;

  public a: any;

  constructor() {
  }


  /* 生成随机数 */
  public randomData() {

    //this.a = new Date(new Date()) ;
    //console.log(this.nowTime);
    this.nowTime = new Date(+this.nowTime + this.timeInterval);
    //console.log(this.nowTime);
    this.randomValue = Math.random() * 21;
    return {
      name: this.nowTime.toString(),
      value: [
        [this.nowTime.getFullYear(), this.nowTime.getMonth() + 1, this.nowTime.getDate()].join('/'),
        Math.round(this.randomValue)
      ]
    }

  }


  /* 获取模拟数据 */
  public getMockData() {
    for (let i = 0; i < 100; i++) {
      this.mockData.push(this.randomData());
    }
    //console.log(this.mockData);
    return this.mockData;
  }

  /* 获取图表实例 */
  public onChartInit(ec) {
    this.echartsInstance = ec;
  }

  public onChartInit3(ec3) {
    this.echartsInstance3 = ec3;

  }

  /* 更新数据并重绘动态折线图 */
  public redrawChart() {
    if (this.echartsInstance) {
      this.echartsInstance.setOption({
        series: [{
          data: this.mockData
        }]
      });
    }
  }

  /* 更新数据并重绘动态折线图+条形图 */
  public redrawChart3() {
    if (this.echartsInstance3) {
      this.echartsInstance3.setOption(this.linechartOptions3);
    }
  }


  ngOnInit() {
    /**
     * **************************************************************
     * 堆叠图
     * **************************************************************
     */
    this.linechartOptions = {
      title: {
        text: '堆叠区域图'
      },
      /* 提示框 */
      tooltip: {
        trigger: 'axis' // 坐标轴触发
      },
      /* 图例组件 */
      legend: {
        data: ['邮件营销']
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          axisLine: {
            show: false // 不显示坐标轴轴线
          },
          axisTick: {
            show: false // 不显示坐标轴刻度
          },
          axisLabel: {
            color: '#636363' //坐标轴刻度标签颜色
          },
        }
      ],
      yAxis: [
        {
          type: 'value',
          splitLine: {
            show: true // 显示分隔线
          },
          axisLine: {
            show: false // 不显示坐标轴轴线
          },
          axisTick: {
            show: false // 不显示坐标轴刻度
          },
          axisLabel: {
            color: '#636363' //坐标轴刻度标签颜色
          },
        }
      ],
      series: [
        {
          name: '邮件营销',
          type: 'line',
          stack: '总量',
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'blue' // 0% 处的颜色
                }, {
                  offset: 1, color: 'skyblue' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              }
            }
          },
          lineStyle: {
            normal: {
              color: 'auto'
            }
          },
          showSymbol: false,
          data: [120, 132, 101, 134, 90, 230, 210]
        }
      ]
    };


    /**
     * **************************************************************
     * 动态折线图
     * **************************************************************
     */
    this.getMockData();

    /* 定义配置项-- 动态折线图 */
    this.linechartOptions2 = {
      title: {
        text: 'SERVER'
      },
      /* 提示框 */
      tooltip: {
        trigger: 'axis', // 坐标轴触发
        formatter: (params) => {
          params = params[0];
          let date = new Date(params.name);
          return '时间' + date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' 数值:' + params.value[1]
        },
        axisPointer: {
          z: -1
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'time',
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        boundaryGap: [0, '100%'],
        splitLine: {
          show: false
        }
      },
      series: [{
        name: '模拟数据',
        type: 'line',
        showSymbol: true,
        symbol: 'circle', //拐点样式为实心圆
        symbolSize: 5, //圆点的大小
        /* 设置折线拐点样式 */
        itemStyle: {
          normal: {
            color: 'blue' // 圆点的颜色
          }
        },
        /* 设置折线样式 */
        lineStyle: {
          normal: {
            color: 'orange', //折线颜色
            width: 2,
          }
        },
        hoverAnimation: true,
        data: this.mockData,

      }]
    };

    /* 每隔5s刷新数据 */
    setInterval(() => {
      //console.log(this.mockData);
      for (let i = 0; i < 100; i++) {
        this.mockData.shift();
      }
      this.getMockData(); // 获取模拟数据

      this.redrawChart(); // 重绘

    }, 5000);


    /**
     * **************************************************************
     * 动态折线图+条形图
     * **************************************************************
     */


    /* 定义配置项-- 动态折线图+条形图 */
    this.linechartOptions3 = {
      /* 标题 */
      title: {
        text: '能耗统计',
        left: 'center'  // 居中
      },
      /* 提示框 */
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          label: {
            backgroundColor: '#283b56'
          },
          z: -1
        }
      },

      /* 图例 */
      legend: {
        show: true,
        data: ['输出功率', '输入功率', '能耗利用率'],
        bottom: 5
      },

      /* 定义x轴*/
      xAxis: {
        type: 'category', // 类目轴
        boundaryGap: true, // 留白
        data: (function () {
          let now = new Date();
          let res = [];
          let len = 10; // 定义x轴分段数量
          while (len--) {
            //res.unshift(now.toLocaleTimeString().replace(/^\D*/,'')); // 输出12h制时分秒
            let currentMin = now.getMinutes();
            let minStr = currentMin > 9 ? currentMin : '0' + currentMin;
            res.unshift(now.getHours() + ':' + minStr);
            now = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() - 1, now.getSeconds());
          }
          return res;
        })()
      },

      /* 定义y轴 */
      yAxis: [{
        type: 'value',
        scale: true,
        name: '功率',
        max: 1000,
        min: 0,
        boundaryGap: [0.2, 0.2]
      },
        {
          type: 'value',
          scale: true,
          name: '能耗利用率',
          max: 10,
          min: 0,
          boundaryGap: [0.2, 0.2]
        }],

      /* 系列列表，通过type定义不同的图表类型 */
      series: [
        /* 条形图数据 */
        {
          name: '输出功率',
          type: 'bar',
          yAxisIndex: 0,
          itemStyle: {
            normal: {
              color: '#4472C4'
            }
          },
          data: (function () {
            let res = [];
            let len = 10;
            while (len--) {
              res.push(Math.round(Math.random() * 1000));
            }
            return res;
          })()
        },

        /* 条形图数据 */
        {
          name: '输入功率',
          type: 'bar',
          barGap: '30%',
          barWidth: '20px',
          yAxisIndex: 0,
          itemStyle: {
            normal: {
              color: '#ED7D31'
            }
          },
          data: (function () {
            let res = [];
            let len = 10;
            while (len--) {
              res.push(Math.round(Math.random() * 1000));
            }
            return res;
          })()
        },

        /* 折线图数据 */
        {
          name: '能耗利用率',
          type: 'line',
          yAxisIndex: 1,
          showSymbol: true,
          symbol: 'circle', //拐点样式为实心圆
          symbolSize: 3, //圆点的大小
          /* 设置折线拐点样式 */
          itemStyle: {
            normal: {
              color: 'red' // 圆点的颜色
            }
          },
          /* 设置折线样式 */
          lineStyle: {
            normal: {
              color: 'red', //折线颜色
              width: 2,
            }
          },
          data: (function () {
            let res = [];
            let len = 0;
            while (len < 10) {
              res.push(Math.random() * 5);
              len++;
            }
            return res;
          })()
        }
      ]
    };


    /* 每1min 更新数据 */
    setInterval(() => {

      let axisData = (new Date()).getHours() + ':' + (new Date()).getMinutes();
      console.log(axisData);
      let barData = this.linechartOptions3.series[0].data;
      let lineData = this.linechartOptions3.series[1].data;
      barData.shift();
      barData.push(Math.round(Math.random() * 1000)); // 更新条形图数据
      lineData.shift();
      lineData.push((Math.random() * 50 + 5)); // 更新折线图数据
      this.linechartOptions3.xAxis.data.shift();
      this.linechartOptions3.xAxis.data.push(axisData);

      this.redrawChart3();
    }, 60 * 1000)


  }


}
